import environment from '../environments'
import { userStore } from '@/store/modules/user'
const baseUrl = environment.url
const getHeader = () => {
    // 目前只存放token
    const { token } = userStore()
    return token ? { Authorization: token } : {}
}

/**
 *
 * @param url  请求的地址
 * @param data 请求的数据
 * @param type 请求类型,需要大写
 * @param config
 *
 * hideLoading 默认在请求的时候有loading,hideLoading为true将隐藏loading
 *
 * header  header信息
 *
 * timeout 超时时间,默认6000
 */
const request = (
    url: string,
    data?: any,
    type: 'POST' | 'OPTIONS' | 'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' = 'POST',
    config?: { hideLoading?: boolean; header?: any; timeout?: number }
) =>
    new Promise<void>((resolve, reject) => {
        const method = type //uniapp的uni.request必须大写
        if (!config?.hideLoading) {
            uni.showLoading({
                title: '加载中...',
            })
        }
        const setHeader = config?.header || {}

        const header = { ...getHeader(), ...setHeader }

        const timeout = config?.timeout || 6000

        uni.request({
            url: `${baseUrl}${url}`,
            method,
            data,
            header,
            timeout,
            success(res) {
                // 请求成功
                const { data }: any = res
                if (data.status) {
                    //隐藏加载
                    if (!config?.hideLoading) uni.hideLoading()
                    resolve(data)
                } else if (data.code === '1002') {
                    // 重新登录
                    uni.showToast({ title: '请重新登录!', icon: 'error', duration: 3000 })
                    uni.reLaunch({ url: '/pages/login/index' })
                    userStore().logout()
                } else {
                    // 其他异常
                    uni.showToast({ title: data.messages, icon: 'none', duration: 3000 })
                    reject(data)
                }
            },

            fail(err) {
                console.log(err)
                uni.showToast({ title: '请求失败!', icon: 'error', duration: 3000 })
                if (!config?.hideLoading) uni.hideLoading()
                // 请求失败
                reject(new Error('请检查网络'))
            },
        })
    })

export default request
